<?php

namespace app\adminapi\logic\room\department;

use app\common\enum\DefaultEnum;
use app\common\logic\BaseLogic;
use app\common\model\room\department\Department;
use think\facade\Db;


/**
 * 科室管理逻辑
 * Class RoomDepartmentLogic
 * @package app\adminapi\logic\room
 */
class DepartmentLogic extends BaseLogic
{


    /**
     * @notes 添加科室管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            Department::create([
                'cid'       => $params['cid'] ?? 0,
                'name'      => $params['name'] ?? '',
                'code'      => $params['code'] ?? '',
                'status'    => $params['status'] ?? DefaultEnum::SHOW,
                'sort'      => $params['sort'] ?? 1,
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑科室管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            Department::where('id', $params['id'])->update([
                'cid'       => $params['cid'] ?? 0,
                'name'      => $params['name'] ?? '',
                'code'      => $params['code'] ?? '',
                'status'    => $params['status'] ?? DefaultEnum::SHOW,
                'sort'      => $params['sort'] ?? 1,
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除科室管理
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function delete(array $params): bool
    {
        return Department::destroy($params['id']);
    }


    /**
     * @notes 获取科室管理详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public static function detail($params): array
    {
        return Department::findOrEmpty($params['id'])->toArray();
    }

    /**
     * 编辑科室状态
     *
     * @param array $params
     * @return void
     */
    public static function updateStatus(array $params)
    {
        Department::update([
            'id' => $params['id'],
            'status' => $params['status']
        ]);
        return true;
    }
}
